//
//  AppDelegate.m
//  Piece
//
//  Created by dllo on 16/6/6.
//  Copyright © 2016年 Northeast Dianli University. All rights reserved.
//

#import "AppDelegate.h"
#import "DXYHomeViewController.h"
#import "DXYReadViewController.h"
#import "DXYMusicViewController.h"
#import "DXYMovieViewController.h"
#import "AudioPlayerManager.h"

#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>

//腾讯开放平台（对应QQ和QQ空间）SDK头文件
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>

//微信SDK头文件
#import "WXApi.h"

//新浪微博SDK头文件
#import "WeiboSDK.h"
#import "ZHNetworkHandler.h"
#import "ZHBaseViewController.h"
#import "JXLDayAndNightMode.h"
#import "ZWIntroductionViewController.h"

//新浪微博SDK需要在项目Build Settings中的Other Linker Flags添加"-ObjC"


@interface AppDelegate ()<AudioPlayerManagerDelegate, musicPlayViewDelegate, XZHMusicPlayViewDelegate>

@property (nonatomic, retain) ZWIntroductionViewController *introductionView;

@property (nonatomic, strong) AudioPlayerManager *playerManager;
@property (nonatomic, assign) NSInteger tempIndex;
@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    DXYHomeViewController *homeVC = [[DXYHomeViewController alloc] init];
    homeVC.delegate = self;
    UINavigationController *homeNVC = [[UINavigationController alloc] initWithRootViewController:homeVC];
    homeNVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"首页" image:[UIImage imageNamed:@"tab_home_normal"] selectedImage:[[UIImage imageNamed:@"tab_home_selected"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    
    DXYReadViewController *readVC = [[DXYReadViewController alloc] init];
    readVC.delegate = self;
    UINavigationController *readNVC = [[UINavigationController alloc] initWithRootViewController:readVC];
    readNVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"阅读" image:[UIImage imageNamed:@"tab_read_normal"] selectedImage:[[UIImage imageNamed:@"tab_read_selected"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    
    DXYMusicViewController *musicVC = [[DXYMusicViewController alloc] init];
    musicVC.delegate = self;
    UINavigationController *musicNVC =[[UINavigationController alloc] initWithRootViewController:musicVC];
    musicNVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"音乐" image:[UIImage imageNamed:@"tab_music_normal"] selectedImage:[[UIImage imageNamed:@"tab_music_selected"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    
    DXYMovieViewController *movieVC = [[DXYMovieViewController alloc] init];
    movieVC.delegate = self;
    UINavigationController *movieNVC = [[UINavigationController alloc] initWithRootViewController:movieVC];
    movieNVC.tabBarItem = [[UITabBarItem alloc] initWithTitle:@"电影" image:[UIImage imageNamed:@"tab_movie_normal"] selectedImage:[[UIImage imageNamed:@"tab_movie_selected"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
    
    UITabBarController *tab = [[UITabBarController alloc] init];
    tab.viewControllers = @[homeNVC, readNVC, musicNVC, movieNVC];
    
    tab.tabBar.translucent = NO;
    tab.tabBar.tintColor = [UIColor colorWithRed:0.54 green:0.69 blue:0.84 alpha:1.00];
    
    [[UINavigationBar appearance] setTranslucent:NO];
    [[UINavigationBar appearance] setBarTintColor:[UIColor whiteColor]];
    
    
    //设置引导页
    NSArray *coverImageNames = @[@"guide_text1", @"guide_text2", @"guide_text3", @"guide_text4"];
    NSArray *backgroundImageNames = @[@"guide1", @"guide2", @"guide3",@"guide4"];
    self.introductionView = [[ZWIntroductionViewController alloc] initWithCoverImageNames:coverImageNames backgroundImageNames:backgroundImageNames];
    [self.window addSubview:self.introductionView.view];
    DXYWeakSelf
    self.introductionView.didSelectedEnter = ^() {
        
        UIView *dayAndNightView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
        dayAndNightView.userInteractionEnabled = NO;
        [weakSelf.window addSubview:dayAndNightView];
        
        [dayAndNightView jxl_setDayMode:^(UIView *view) {
            // 设置日间模式状态
            dayAndNightView.backgroundColor = [UIColor clearColor];
        } nightMode:^(UIView *view) {
            // view为当前设置的视图
            // 设置夜间模式状态
            view.backgroundColor = [UIColor colorWithRed:0.23 green:0.22 blue:0.22 alpha:0.40];
        }];
        
        
        [weakSelf.introductionView.view removeFromSuperview];
        weakSelf.introductionView = nil;
        weakSelf.window.rootViewController = tab;
        //创建音乐播放界面
        weakSelf.playView = [XZHMusicPlayView shareMusicPlayViewInstance];
        weakSelf.playView.hidden = YES;
        weakSelf.playView.delegate = weakSelf;
        UITapGestureRecognizer *tapClearView = [[UITapGestureRecognizer alloc] initWithTarget:weakSelf action:@selector(didTapView)];
        [weakSelf.playView addGestureRecognizer:tapClearView];
        [weakSelf.window addSubview:weakSelf.playView];
        [weakSelf.window bringSubviewToFront:weakSelf.playView];
    };
    //判断是不是第一次启动应用
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstLaunch"])
    {
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstLaunch"];
        //        如果是第一次启动的话,使用UserGuideViewController (用户引导页面) 作为根视图
        self.window.rootViewController = self.introductionView;
    }else {
        //        如果不是第一次启动的话,使用作为根视图
        self.window.rootViewController = tab;
    }
//    self.window.rootViewController = tab;
    //创建音乐播放界面
    self.playView =  [XZHMusicPlayView shareMusicPlayViewInstance];
        self.playView.hidden = YES;
        self.playView.delegate = self;
    UITapGestureRecognizer *tapClearView = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTapView)];
    [self.playView addGestureRecognizer:tapClearView];
    [self.window addSubview:_playView];
    [self.window bringSubviewToFront:self.playView];
    
    UIView *dayAndNightView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    dayAndNightView.userInteractionEnabled = NO;
    [self.window addSubview:dayAndNightView];
    
    [dayAndNightView jxl_setDayMode:^(UIView *view) {
        // 设置日间模式状态
        dayAndNightView.backgroundColor = [UIColor clearColor];
    } nightMode:^(UIView *view) {
        // view为当前设置的视图
        // 设置夜间模式状态
        view.backgroundColor = [UIColor colorWithRed:0.23 green:0.22 blue:0.22 alpha:0.40];

    }];
    
    
    
    [self shareMessage];
    return YES;
}

- (void)didTapView {
    self.playView.hidden = YES;
}

- (void)createMusicPlayView
{
    self.playView.hidden = NO;
}
//音乐播放单例
+ (AppDelegate *)shareDetailViewController
{
   
    static AppDelegate *detail = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        detail = [[AppDelegate alloc] init];
    });
    
    return detail;
}

//点击播放上一首
- (void)lastMusic
{
    _playView.index --;
    if (_playView.index == -1) {
        _playView.index = _playView.musicArr.count - 1;
    }
    NSLog(@"index---%ld", _playView.index);
    NSString *idList = [_playView.musicArr objectAtIndex:_playView.index];
    NSLog(@"idList--%@", idList);
    [self playMusicByIdList:idList];
    _playView.isPlay = YES;
    _playView.pauseButton.hidden = NO;
    _playView.playButton.hidden = YES;
    NSLog(@"上一曲");

}
//点击播放下一曲
- (void)nextMusic
{
    NSLog(@"playView-arr---%@", _playView.musicArr);
    _playView.index ++;

    if (_playView.index == _playView.musicArr.count) {
        _playView.index = 0;
    }
    NSLog(@"index---%ld", _playView.index);
    NSString *idList = [_playView.musicArr objectAtIndex:_playView.index];
     NSLog(@"idList--%@", idList);
    [self playMusicByIdList:idList];
    _playView.isPlay = YES;
    _playView.pauseButton.hidden = NO;
    _playView.playButton.hidden = YES;
    NSLog(@"下一曲");
}
//点击播放
- (void)playMusic
{
    self.playerManager = [AudioPlayerManager shareAudioPlayerManager];
    self.playerManager.delegate = self;
    [self.playerManager play];
}
//点击暂停
- (void)pauseMusic
{
    self.playerManager = [AudioPlayerManager shareAudioPlayerManager];
    self.playerManager.delegate = self;
    [self.playerManager pause];
}
- (void)playMusicByIdList:(NSString *)idList
{
    DXYWeakSelf
    NSString *urlString = [NSString stringWithFormat:@"http://v3.wufazhuce.com:8000/api/music/detail/%@", idList];
    NSLog(@"urlString---%@", urlString);
    [ZHNetworkHandler getDataByURLString:urlString WithBodyString:nil WithHeaderDic:nil WithResponse:ZHJSON WithSuccess:^(id result) {
        
        NSDictionary *diction = [result objectForKey:@"data"];
        
        weakSelf.musicInfo = [[YXJMusicModel alloc] initWithDic:diction];
        if (_musicInfo.platform == 1) {
            _musicInfo.music_id = @"http://audio.xmcdn.com/group4/M02/10/EF/wKgDtFMnpi6Ais1VAA6eW1LeOVg178.mp3";
        }
        _playView.titleLabel.text = _musicInfo.title;
        //[weakSelf.playerManager stop];
        [weakSelf playerStop];
        // 播放音频
        NSLog(@"music_id---%@",weakSelf.musicInfo.music_id);
        [weakSelf.playerManager playerPlayWithUrl:weakSelf.musicInfo.music_id];
        NSLog(@"!!!!!!!!!!!播放");
        
        
        
    } WithFailure:^(NSError *error) {
        
    }];
}

#pragma 设置播放器终止播放
- (void)playerStop
{
    // 让播放器终止
    [self.playerManager stop];
}

- (void)didFinshPlay
{
    NSLog(@"--_playView.musicArr---%@",_playView.musicArr);
    if (!_playView.isCirulate) {
       
        [self playerStop];
        _playView.index ++;
        if (_playView.index == _playView.musicArr.count) {
            _playView.index = 0;
        }
        NSString *idList = [_playView.musicArr objectAtIndex:_playView.index];
        [self playMusicByIdList:idList];
        
        NSLog(@"!!!!!!!!!!!自动播放下一首");

    }
    else
    {
        [self.playerManager playerPlayWithUrl:_musicInfo.music_id];
    }
}

// 播放
- (void)setMusicInfo:(YXJMusicModel *)musicInfo
{
    if (musicInfo != _musicInfo) {
        _musicInfo = musicInfo;
        self.playerManager = [AudioPlayerManager shareAudioPlayerManager];
        self.playerManager.delegate = self;
        [self playerStop];
        
        // 播放音频
        NSLog(@"music_id!!!!!!!!!!%@",self.musicInfo.music_id);
        [self.playerManager playerPlayWithUrl:self.musicInfo.music_id];
        NSLog(@"!!!!!!!!!!!播放");
    }
}

#pragma mark -- 分享信息
- (void)shareMessage
{
    [ShareSDK registerApp:@"iosv1101"
     
          activePlatforms:@[
                            @(SSDKPlatformTypeSinaWeibo),
                            @(SSDKPlatformTypeMail),
                            @(SSDKPlatformTypeSMS),
                            @(SSDKPlatformTypeCopy),
                            @(SSDKPlatformTypeWechat),
                            @(SSDKPlatformTypeQQ),
                            @(SSDKPlatformTypeRenren),
                            @(SSDKPlatformTypeGooglePlus)]
                 onImport:^(SSDKPlatformType platformType)
     {
         switch (platformType)
         {
             case SSDKPlatformTypeWechat:
                 [ShareSDKConnector connectWeChat:[WXApi class]];
                 break;
             case SSDKPlatformTypeQQ:
                 [ShareSDKConnector connectQQ:[QQApiInterface class] tencentOAuthClass:[TencentOAuth class]];
                 break;
             case SSDKPlatformTypeSinaWeibo:
                 [ShareSDKConnector connectWeibo:[WeiboSDK class]];
                 break;
             default:
                 break;
         }
     }
          onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo)
     {
         
         switch (platformType)
         {
             case SSDKPlatformTypeSinaWeibo:
                 //设置新浪微博应用信息,其中authType设置为使用SSO＋Web形式授权
                 [appInfo SSDKSetupSinaWeiboByAppKey:@"3847618028"
                                           appSecret:@"ee5365ac9f962150c4cf6c5bd4da2ae0"
                                         redirectUri:@"http://www.jianshu.com/users/8763aac98cf7/latest_articles"
                                            authType:SSDKAuthTypeBoth];
                 break;
             case SSDKPlatformTypeWechat:
                 [appInfo SSDKSetupWeChatByAppId:@"wxaf44ceef341ed9e5"
                                       appSecret:@"f0012553a249d5246b5144320d0f7bd7"];
                 break;
             case SSDKPlatformTypeQQ:
                 [appInfo SSDKSetupQQByAppId:@"100371282"
                                      appKey:@"aed9b0303e3ed1e27bae87c33761161d"
                                    authType:SSDKAuthTypeBoth];
                 break;
             case SSDKPlatformTypeRenren:
                 [appInfo        SSDKSetupRenRenByAppId:@"226427"
                                                 appKey:@"fc5b8aed373c4c27a05b712acba0f8c3"
                                              secretKey:@"f29df781abdd4f49beca5a2194676ca4"
                                               authType:SSDKAuthTypeBoth];
                 break;
             case SSDKPlatformTypeGooglePlus:
                 [appInfo SSDKSetupGooglePlusByClientID:@"232554794995.apps.googleusercontent.com"
                                           clientSecret:@"PEdFgtrMw97aCvf0joQj7EMk"
                                            redirectUri:@"http://localhost"];
                 break;
             default:
                 break;
         }
     }];
    

}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}

#pragma mark - Core Data stack

@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

- (NSURL *)applicationDocumentsDirectory {
    // The directory the application uses to store the Core Data store file. This code uses a directory named "cn.edu.nedu.Piece" in the application's documents directory.
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

- (NSManagedObjectModel *)managedObjectModel {
    // The managed object model for the application. It is a fatal error for the application not to be able to find and load its model.
    if (_managedObjectModel != nil) {
        return _managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"Piece" withExtension:@"momd"];
    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return _managedObjectModel;
}

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it.
    if (_persistentStoreCoordinator != nil) {
        return _persistentStoreCoordinator;
    }
    
    // Create the coordinator and store
    
    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"Piece.sqlite"];
    NSError *error = nil;
    NSString *failureReason = @"There was an error creating or loading the application's saved data.";
    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {
        // Report any error we got.
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data";
        dict[NSLocalizedFailureReasonErrorKey] = failureReason;
        dict[NSUnderlyingErrorKey] = error;
        error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict];
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    
    return _persistentStoreCoordinator;
}


- (NSManagedObjectContext *)managedObjectContext {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (!coordinator) {
        return nil;
    }
    _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    return _managedObjectContext;
}

#pragma mark - Core Data Saving support

- (void)saveContext {
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil) {
        NSError *error = nil;
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
            // Replace this implementation with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        }
    }
}

@end
